import axios from "axios";

const UrlConfig = () => {
  let BASE_URL = "/api";
  let isPro = process.env.NODE_ENV === "production";
  if (isPro) {
    BASE_URL = "/gate";
  }
  return BASE_URL;
};

const BaseErr = error => {
  window.console.log(error);
};

const http = {
  post(url, params, then, err) {
    axios({
      method: "post",
      url: url,
      data: params,
      timeout: 5000,
      baseURL: UrlConfig(),
      headers: {
        "Content-Type": "application/json; charset=UTF-8"
      },
      withCredentials: true,
      crossDomain: true
    })
      .then(res => {
        let data = res.data;
        then(data);
      })
      .catch(error => {
        if (err != null && typeof err != "undefined") {
          err(error);
        } else {
          BaseErr(error);
        }
      });
  },

  put(url, params, then, err) {
    axios({
      method: "put",
      url: url,
      data: params,
      timeout: 5000,
      baseURL: UrlConfig(),
      headers: {
        "Content-Type": "application/json; charset=UTF-8"
      },
      withCredentials: true,
      crossDomain: true
    })
      .then(res => {
        let data = res.data;
        then(data);
      })
      .catch(error => {
        if (err != null && typeof err != "undefined") {
          err(error);
        } else {
          BaseErr(error);
        }
      });
  },

  get(url, then, err) {
    axios({
      method: "get",
      url: url,
      data: null,
      timeout: 5000,
      baseURL: UrlConfig(),
      headers: {
        "Content-Type": "application/json; charset=UTF-8"
      },
      withCredentials: true,
      crossDomain: true
    })
      .then(res => {
        let data = res.data;
        then(data);
      })
      .catch(error => {
        if (err != null && typeof err != "undefined") {
          err(error);
        } else {
          BaseErr(error);
        }
      });
  },

  del(url, then, err) {
    axios({
      method: "delete",
      url: url,
      data: null,
      timeout: 5000,
      baseURL: UrlConfig(),
      headers: {
        "Content-Type": "application/json; charset=UTF-8"
      },
      withCredentials: true,
      crossDomain: true
    })
      .then(res => {
        let data = res.data;
        then(data);
      })
      .catch(error => {
        if (err != null && typeof err != "undefined") {
          err(error);
        } else {
          BaseErr(error);
        }
      });
  },

  makeParams(map) {
    let str = "?";
    for (let key in map) {
      // eslint-disable-next-line no-prototype-builtins
      if (map.hasOwnProperty(key)) {
        if (map[key] != null) {
          str += key + "=" + map[key] + "&";
        }
      }
    }
    str = str.substr(0, str.length - 1);
    return str;
  }
};

export default http;
